<?php

/**
 * contact : 刘经理 19326416371
 * company : 版权所属 四川北星惯牌科技有限公司
 **/

namespace app\common\manager;

use app\admin\model\Team;
use app\common\constant\Constant;
use app\common\model\Authentication;
use app\common\model\CaptainApplication;
use app\common\model\User;
use app\common\model\UserTeam;
use app\common\model\WriteOff;
use think\Db;
use think\Exception;

class CaptainManager extends BaseManager
{

    /**
     * 实名认证
     * @param int $userId 用户uid
     * @param bool $trans 是否开启事务
     * @return array
     */
    public static function AuthRealName(int $userId,bool $trans=true):array
    {
        if ($trans){
            Db::startTrans();
        }
        try {;
            $captainInfo = CaptainApplication::where('user_id',$userId)->order('id desc')->find();
            if (isset($captainInfo) && $captainInfo['status'] == CaptainApplication::STATUS_AUTO_REAL_NAME){
                throw new Exception('您已申请队长入驻，请等待工作人员审核');
            }
            if (isset($captainInfo) && $captainInfo['status'] == CaptainApplication::STATUS_REVIEWED_SUCCESS){
                throw new Exception('您已入驻队长，请勿重复操作');
            }

            $userAuthentication = Authentication::where('user_id',$userId)->find();
            if (!$userAuthentication){
                throw new Exception('未实名认证，不可申请队长入驻');
            }
            CaptainApplication::create([
                'user_id' => $userId,
                'name' => $userAuthentication->real_name,
                'idcard' => $userAuthentication->id_card,
                'status' => CaptainApplication::STATUS_AUTO_REAL_NAME,
                'create_time' => time(),
                'update_time' => time()
            ]);
            if ($trans)
                Db::commit();
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
        }catch (Exception $exception){
            if ($trans){
                Db::rollback();
            }
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
        }

        return ['code'=>self::getStatusCode(),'message'=>self::getMessage()];
    }

    /**
     * 通过用户id 获取用户入驻信息
     * @param $userId
     * @return array
     */
    public static function getCaptain($userId)
    {

        try {
            $captainInfo = CaptainApplication::where('user_id',$userId)->field('status,reviewer_reason')->order('id desc')->find();
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
            self::setData($captainInfo);
        }catch (Exception $exception){
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
        }
        return ['code'=>self::getStatusCode(),'message'=>self::getMessage(),'data'=>self::getData()];
    }

    /**
     * 个人组队
     * @param User $user 用户信息
     * @param array $data 数据
     * @param int $store_id 门店id
     * @return void
     */
    public static function CaptainTeam(User $user,array $data,int $store_id=0)
    {
        try {

            if (!$user->is_authentication){
                throw new Exception('您未实名认证，无法发起组队');
            }

            if (!$user->is_captain){
                throw new Exception('您不是队长，无法组队，请前往个人中心实名后申请入驻队长');
            }

        }catch (Exception $exception){

        }
    }

    public static function getWriteOffRecord($userId,$page=1,$step=Constant::PAGE_LIMIT)
    {
        $return = ['total'=>0,'totalPage'=>1,'currentPage'=>$page,'list'=>[]];
        if ($page < 1)
            $page = 1;
        try {
            $start = ($page - 1) * $step;
            $writeOffModel = new WriteOff();
            $count = $writeOffModel->alias('wo')
                ->join('user_team ut','ut.ut_id=wo.relation_id','inner')
                ->join('team t','t.t_id=ut.team','left')
                ->join('user u','ut.user_id=u.id','left')
                ->where('wo.type',WriteOff::TYPE_TEAM)
                ->where('wo.writer',$userId)
                ->where('ut.user_id','<>',$userId)
                ->count();

            $info = $writeOffModel->alias('wo')
                ->join('user_team ut','ut.ut_id=wo.relation_id','inner')
                ->join('team t','t.t_id=ut.team','left')
                ->join('user u','ut.user_id=u.id','left')
                ->where('wo.type',WriteOff::TYPE_TEAM)
                ->where('wo.writer',$userId)
                ->where('ut.user_id','<>',$userId)
                ->field('t.title,wo.create_time,u.nickname,ut.team')
                ->limit($start,$step)->select();
            $pageData = page($count,$step,$page);

            $return['list'] = $info;
            $return = array_merge($return,$pageData);

            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
            self::setData($return);
        }catch (Exception $exception){
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
        }
        return ['code'=>self::getStatusCode(),'message'=>self::getMessage(),'data'=>self::getData() ];
    }
}